<?php

namespace app\api\controller;

use think\Db;
use app\common\controller\Api;

/**
 * 市场部
 */
class Market extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['analysis', 'getAnalysisList', 'getCustomerList', 'getContractList'];

    /**
     * 图标统计数据
     *
     * @return void
     */
    public function analysis()
    {
        $type = $this->request->param('type/d', 1); // 1月,2季度,3年
        $year = $this->request->param('year/s', date('Y'));
        $season = $this->request->param('season/s', 1); // 季度数1~4
        $month = $this->request->param('month/s', date('m')); //月分（1~12）
        // 1月,2季度,3年
        switch ($type) {
                // +0为了返回为int类型数据
            case '1':
                [$start, $end] = getMonthStartToEnd($year, $month);
                $format = "FROM_UNIXTIME(createtime,'%u')+0 as date";
                $range = array_range(date('W', $start), date('W', $end));
                $range_str = array_map(function ($item) {
                    return "第{$item}周";
                }, $range);
                break;
            case '2':
                [$start, $end] = getQuarter($year, $season);
                $format = "FROM_UNIXTIME(createtime,'%m')+0 as date";
                $quarter_month = [
                    1 => [1, 2, 3],
                    2 => [4, 5, 6],
                    3 => [7, 8, 9],
                    4 => [10, 11, 12],
                ];
                $range = $quarter_month[$season] ?? [1, 2, 3];
                $range_str = array_map(function ($item) {
                    return "{$item}月";
                }, $range);
                break;
            case '3':
                [$start, $end] = getYearStartToEnd($year);
                $format = "quarter(FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s'))+0 as date";
                $range = [1, 2, 3, 4];
                $range_str = array_map(function ($item) {
                    return "第{$item}季度";
                }, $range);
                break;
            default:
                return $this->error('参数错误！');
                break;
        }
        $data = [];
        $series = [];
        foreach (['archives', 'archives_orders'] as $tablename) {
            $temp_data = Db::name($tablename)->field([
                $format,
                'count(*) as total'
            ])
                ->whereTime('createtime', 'between', [$start, $end])
                ->group('date')
                ->select();

            $all_data = array_column((array) $temp_data, 'date');
            foreach ($range as $num) {
                if (!in_array($num, $all_data)) {
                    $temp_data[] = [
                        'date' => $num,
                        'total' => 0
                    ];
                }
            }
            $data[$tablename] = arraySort($temp_data, 'date', SORT_ASC);
            $series[] = [
                'name' => $tablename == 'archives' ? '新增客户数量' : '合同总数量',
                'data' => array_column($data[$tablename], 'total'),
            ];
        }

        $column = [
            'categories' => $range_str,
            'series' => $series
        ];

        return $this->success('ok', compact('data', 'column'));
    }

    /**
     * 统计图下面的列表
     *
     * @return void
     */
    public function getAnalysisList()
    {
        $page = $this->request->param('page/d', 1);
        $limit = $this->limit;
        [$start_time, $end_time] = getTiamStartToEnd($page, $limit);
        $range = getDayRange($start_time, $limit);
        $contract = Db::name('archives_orders')
            ->field([
                'count(*)' => 'total',
                "FROM_UNIXTIME(createtime,'%Y-%m-%d')" => 'date'
            ])
            ->whereTime('createtime', 'between', [$start_time, $end_time])
            ->group('date')
            ->select();
        $customer = Db::name('archives')
            ->field([
                'count(*)' => 'total',
                "FROM_UNIXTIME(createtime,'%Y-%m-%d')" => 'date'
            ])
            ->whereTime('createtime', 'between', [$start_time, $end_time])
            ->group('date')
            ->select();

        $contract_data = arraySort(getDataInTimeSpan($contract, $range), 'date', SORT_DESC);
        $customer_data = arraySort(getDataInTimeSpan($customer, $range), 'date', SORT_DESC);

        $list = array_map(function ($co, $cu) {
            return [
                'date' => $co['date'],
                'contract_total' => $co['total'],
                'customer_total' => $cu['total'],
            ];
        }, $contract_data, $customer_data);

        return $this->success('ok', compact('list'));
    }

    /**
     * 获取某天的新增客户列表
     *
     * @return void
     */
    public function getCustomerList()
    {
        $page = $this->request->param('page/d', 1);
        $date = $this->request->param('date/s', date('Y-m-d'));
        [$start_time, $end_time] = getDayStartToEnd($date);
        $customer = Db::name('archives')
            ->field([
                'id', 'name', 'gender', 'mobile', 'type'
            ])
            ->whereTime('createtime', 'between', [$start_time, $end_time])
            ->page($page, $this->limit)
            ->order('id DESC')
            ->select();
        return $this->success('ok', compact('customer'));
    }

    /**
     * 获取某天的客户订单记录
     *
     * @return void
     */
    public function getContractList()
    {
        $page = $this->request->param('page/d', 1);
        $date = $this->request->param('date/s', date('Y-m-d'));
        $start_time = strtotime("$date 00:00:00");
        $end_time = strtotime("$date 23:59:59");
        $contract = Db::name('archives_orders')
            ->alias('ao')
            ->field([
                'ao.id', 'ao.order_no', 'ao.pay_num', 'ao.finish', 'ao.pay_data', 'a.name'
            ])
            ->join([
                ['fa_archives a', 'a.id = ao.aid', 'LEFT']
            ])
            ->whereTime('ao.createtime', 'between', [$start_time, $end_time])
            ->page($page, $this->limit)
            ->order('ao.id DESC')
            ->select();
        return $this->success('ok', compact('contract'));
    }
}
